import tornado.web
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.escape
import tornado.websocket

from config.settings import *
from api.method_mapping import call


class APIHandler(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    def allow_origin(self):
        self.set_default_headers()
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers",
                        "appid,terminal,token,Token-Seller-Account,Token-Merchant-Employee,sign,"
                        "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, "
                        "Access-Control-Request-Method, Access-Control-Request-Headers")
        self.set_header('Access-Control-Allow-Methods', 'POST,GET,PUT,DELETE,OPTIONS')

    @tornado.gen.coroutine
    def get(self):
        self.allow_origin()
        params = self.request.body.decode('utf-8')
        _r = call(params)
        self.write(_r)

    @tornado.gen.coroutine
    def post(self):
        self.allow_origin()
        params = self.request.body.decode('utf-8')
        _r = call(params)
        self.write(_r)

    @tornado.gen.coroutine
    def options(self, *args, **kwargs):
        self.allow_origin()


class IndexHandler(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    def get(self):
        r_id = self.get_argument('id')
        self.render(r_id + '.html')


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/cmd', APIHandler),
            (r'/result', IndexHandler)
        ]

        settings = dict(
            template_path="template",
            debug=True,
            compiled_template_cache=False,
            autoreloade=True,
            static_hash_cache=False,
            serve_traceback=True)

        tornado.web.Application.__init__(self, handlers, **settings)


if __name__ == '__main__':
    app = Application()
    server = tornado.httpserver.HTTPServer(app)
    port=80
    # server.listen(port)
    # print('start server on {0}'.format(port))
    # tornado.ioloop.IOLoop.instance().start()

    # 多进程方式
    server.listen(port)
    server.start(0)
    print('start server on {0}'.format(port))
    tornado.ioloop.IOLoop.current().start()

